package repository

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Slice"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/periodTask"
)

type RepoScanStatusTask struct {
	ModelType string
}

func (e *RepoScanStatusTask) TaskType() periodTask.TaskType {
	return periodTask.TaskOnce
}

func (e *RepoScanStatusTask) SchedulePeriod() int64 {
	return 1
}

func (e *RepoScanStatusTask) Execute() {
	// 简单验证
	if Method.HasEmpty(e.ModelType) {
		commLogger.Console.Error("参数不能为空: modelType")
		return
	}

	// 删除旧的下载文件
	if "service" == e.ModelType {
		e.deleteJunkFiles(e.ModelType)
	}

	// 下载完成后，验证状态
	CloudFileInstallStatus.ScanRepositoryStatus(e.ModelType)
}

func (e *RepoScanStatusTask) deleteJunkFiles(modelType string) {
	// 名单列表
	localList := CloudCache.ReadList(modelType)

	tables := make([]string, 0)
	for _, data := range localList {
		modelName := Map.GetString(data, "modelName", "")
		component := Map.GetString(data, "component", "")
		versions := Map.GetSlice(data, "versions", make([]interface{}, 0))

		for _, v := range versions {
			entity := v.(map[string]interface{})

			version := Map.GetString(entity, "version", "")
			stage := Map.GetString(entity, "stage", "")
			if Method.HasEmpty(version, stage) {
				continue
			}

			sb := ""
			sb += modelName + "/"
			sb += component + "/"
			sb += version + "/"
			sb += stage

			tables = append(tables, sb)
		}
	}

	// 文件列表
	modelList := LocalPathName.findRepoLocalModelType(modelType)
	for _, data := range modelList {
		modelName := Map.GetString(data, "modelName", "")
		component := Map.GetString(data, "component", "")
		version := Map.GetString(data, "version", "")
		stage := Map.GetString(data, "stage", "")

		sb := ""
		sb += modelName + "/"
		sb += component + "/"
		sb += version + "/"
		sb += stage

		// 根据本地文件是否存在与远端再本地的列表中，判定是否为垃圾文件
		if Slice.Has(tables, sb) {
			continue
		}

		// 删除本地垃圾文件
		//	CloudFileInstallService.DeletePackageFile(modelType, modelName, version, stage, component)
	}
}
